package com.nwpu.intimacy.shake;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.nwpu.intimacy.R;
import com.nwpu.intimacy.shake.ShakeListener.OnShakeListener;
import com.nwpu.intimacy.utils.CacheUtil;

public class ShakeActivity extends Activity {

	private static final String URL = "http://10.128.51.203:8080/SoftwareEngineer/shake";

	private final static int USER_SHAKE_SUCCESS = 0x114;
	private final static int USER_SHAKE_FAIL = 0x115;

	private Handler shakeHandler;

	ShakeListener mShakeListener = null;
	Vibrator mVibrator;
	private RelativeLayout mImgUp;
	private RelativeLayout mImgDn;
	private RelativeLayout mTitle;

	private SharedPreferences sp_userMessage;

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shake);

		// drawerSet ();//设置 drawer监听 切换 按钮的方向

		sp_userMessage = this.getSharedPreferences("userMessage",
				Context.MODE_PRIVATE);

		mVibrator = (Vibrator) getApplication().getSystemService(
				VIBRATOR_SERVICE);

		mImgUp = (RelativeLayout) findViewById(R.id.shakeImgUp);
		mImgDn = (RelativeLayout) findViewById(R.id.shakeImgDown);

		mShakeListener = new ShakeListener(ShakeActivity.this);
		mShakeListener.setOnShakeListener(new OnShakeListener() {
			public void onShake() {

				startAnim(); // 开始 摇一摇手掌动画
				mShakeListener.stop();

				startVibrato(); // 开始 震动
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {

						shakeRequest(sp_userMessage.getString("USER_NAME", ""));

						mVibrator.cancel();
						mShakeListener.start();
					}
				}, 2000);
			}
		});

		// 线程交互
		shakeHandler = new Handler() {

			@SuppressLint("NewApi")
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_SHAKE_SUCCESS: {
					// 跳转界面 登录成功

					try {

						JSONArray jsonArray = new JSONArray(msg.obj.toString());
						CacheUtil.writeToFile(jsonArray.toString(),
								"shakeFriend", "Shake");

						Intent intent = new Intent();
						intent.setClass(getApplicationContext(),
								ShakeListActivity.class);
						startActivity(intent);

						onDestroy();
						finish();

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					break;
				}
				case USER_SHAKE_FAIL: {

					// 没有同时摇动手机的用户，未匹配到指定用户

					Toast.makeText(getApplicationContext(),
							"No found specified user!", Toast.LENGTH_SHORT)
							.show();
					break;

				}
				default:
					super.handleMessage(msg);
				}
			}

		};
	}

	public void startAnim() { // 定义摇一摇动画动画
		AnimationSet animup = new AnimationSet(true);
		TranslateAnimation mytranslateanimup0 = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
				-0.5f);
		mytranslateanimup0.setDuration(1000);
		TranslateAnimation mytranslateanimup1 = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
				+0.5f);
		mytranslateanimup1.setDuration(1000);
		mytranslateanimup1.setStartOffset(1000);
		animup.addAnimation(mytranslateanimup0);
		animup.addAnimation(mytranslateanimup1);
		mImgUp.startAnimation(animup);

		AnimationSet animdn = new AnimationSet(true);
		TranslateAnimation mytranslateanimdn0 = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
				+0.5f);
		mytranslateanimdn0.setDuration(1000);
		TranslateAnimation mytranslateanimdn1 = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
				Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF,
				-0.5f);
		mytranslateanimdn1.setDuration(1000);
		mytranslateanimdn1.setStartOffset(1000);
		animdn.addAnimation(mytranslateanimdn0);
		animdn.addAnimation(mytranslateanimdn1);
		mImgDn.startAnimation(animdn);
	}

	public void startVibrato() {
		MediaPlayer player;
		player = MediaPlayer.create(this, R.raw.aw);
		player.setLooping(false);
		player.start();

		// 定义震动
		mVibrator.vibrate(new long[] { 500, 200, 500, 200 }, -1); // 第一个｛｝里面是节奏数组，
																	// 第二个参数是重复次数，-1为不重复，非-1俄日从pattern的指定下标开始重复
	}

	public void shake_activity_back(View v) { // 标题栏 返回按钮
		this.finish();
	}

	public void linshi(View v) { // 标题栏
		startAnim();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mShakeListener != null) {
			mShakeListener.stop();
		}
	}

	private void shakeRequest(final String username) {

		new Thread() {

			public void run() {

				try {

					// 封装用户信息
					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("username", username);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("shake data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair("shake",
							jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					Log.e("shake", URLDecoder.decode(result, HTTP.UTF_8));

					if (!result.equals("") && !result.equals("[]")) {

						Message msg = new Message();
						msg.what = USER_SHAKE_SUCCESS;
						msg.obj = result;
						shakeHandler.sendMessage(msg);

					} else {

						Message msg = new Message();
						msg.what = USER_SHAKE_FAIL;
						msg.obj = result;
						shakeHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();

	}

}